package com.tcat.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tcat.common.enums.ExceptionEnum;
import com.tcat.common.exception.TcatException;
import com.tcat.common.vo.PageResult;
import com.tcat.item.bo.SpuBo;
import com.tcat.item.mapper.BrandMapper;
import com.tcat.item.pojo.Brand;
import com.tcat.item.pojo.Category;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liysh
 * @date 2020/12/9
 */
@Service
public class BrandService {
    @Autowired
    private BrandMapper brandMapper;

    public PageResult<Brand> queryBrandByPage(Integer page, Integer rows, String sortBy, Boolean desc, String search) {
        //分页
        PageHelper.startPage(page,rows);
        //过滤
        Example example=new Example(Brand.class);
        if(StringUtils.isNotBlank(search)){
            example.createCriteria().orLike("name","%"+search+"%")
                    .orEqualTo("letter",search.toUpperCase());
        }
        //排序
        if(StringUtils.isNotBlank(sortBy)){
            String orderByClause=sortBy +(desc ? " DESC":" ASC");
            example.setOrderByClause(orderByClause);
        }
        //查询
        //分页助手会拦截查询并对他进行分页
        Page<Brand> list = (Page<Brand>)brandMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(list)){
            throw new TcatException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        //解析分页结果
        PageInfo<Brand> info=new PageInfo<>(list);
        return new PageResult<>(info.getTotal(),list);
    }

    /**
     * 新增品牌
     * @param brand
     * @param cids
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBrand(Brand brand, List<Long> cids) {
        //新增品牌
        brand.setId(null);
        int count = brandMapper.insert(brand);
        if(count!=1){
            throw new TcatException(ExceptionEnum.BRAND_SAVE_ERROR);
        }
        //新增中间表
        for(Long cid:cids){
            count = brandMapper.insertCategoryBrand(cid, brand.getId());
            if(count!=1){
                throw  new TcatException((ExceptionEnum.BRAND_SAVE_ERROR));
            }
        }
    }

    /**
     * 品牌更新
     * @param brand
     * @param categories
     */
    @Transactional(rollbackFor=Exception.class)
    public void updateBrand(Brand brand,List<Long> categories){
        deleteByBrandIdInCategoryBrand(brand.getId());
        this.brandMapper.updateByPrimaryKeySelective(brand);
        for(Long cid:categories){
            this.brandMapper.insertCategoryBrand(cid,brand.getId());
        }
    }
    public void deleteByBrandIdInCategoryBrand(Long bid) {
        brandMapper.deleteByBranInCategoryBrand(bid);
    }

    /**
     * 删除品牌  单个（多个删除则每个遍历每个品牌进行删除）
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteBrand(long id) {
        brandMapper.deleteByPrimaryKey(id);
        brandMapper.deleteByBranInCategoryBrand(id);
    }






    /**
     * 根据cid查询品牌
     * @param cid
     * @return
     */
    public List<Brand> queryBrandByCid(Long cid){
        List<Brand> list=brandMapper.queryByCategoryId(cid);
        if(CollectionUtils.isEmpty(list)){
            throw new TcatException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return list;
    }




    public Brand queryById(Long id){
        Brand brand=brandMapper.selectByPrimaryKey(id);
        if(brand == null){
            throw new TcatException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return brand;
    }


    public List<Brand> queryByIds(List<Long> ids) {
        List<Brand> list=brandMapper.selectByIdList(ids);
        if(CollectionUtils.isEmpty(list)){
            throw new TcatException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return list;
    }



    public int countBrands(){
        return brandMapper.selectAll().size();
    }







}
